<?php

class ChatDetail extends AbstractBox {
	protected $template = 'message/chat_detail.tpl';
	
	/**
	 * @var	tslib_pibase
	 */
	protected $cObject = NULL;
	
	public function __construct($cObject) {
		$this->cObject = $cObject;
	}
	
	protected function setup() {
		$loggedUser = LoggedUser::whoIsLogged();
		if (!$loggedUser) {
			Utils::redirect('uvod.html');
		}

		if (Utils::post('chat')) {
			$data = Utils::post();
			$validation = $this->validateChatForm($data);
			if ($validation !== TRUE) {
				MySmarty::assign('errors', $validation);
			} else {
				$data = $this->prepareDataToSave($data);
				$message = new Message($data);
				$message->save();
				Utils::redirect(Utils::getActualUrlWithoutGetParameters(), FALSE);
			}
		}
		
		MySmarty::assign('loggedUser', $loggedUser);
		
		$userRepository = new UserRepository();
		$user = $userRepository->getOneByUsername(Utils::get('alias'));
		MySmarty::assign('toUser', $user);
		
		$messageRepository = new MessageRepository();
		$messageRepository->addOrderBy(array('crdate' => 'desc'));
		$messageList = $messageRepository->getByFkFromUserIdAndFkToUserId(
			array($loggedUser['uid'], $user['uid']), array($loggedUser['uid'], $user['uid'])
		);
		
		// nastavime spravy od usera user aktualnemu userovi ako precitane v case time()
		$query = 'UPDATE message SET is_read = ' . time() . '
			WHERE is_read = 0 AND deleted = 0 AND hidden = 0 AND fk_from_user_id = ' . $user['uid'] . ' AND fk_to_user_id = ' . $loggedUser['uid'];
		DB::query($query);
		
		MySmarty::assign('messageList', $messageList);
	}
	
	protected function validateChatForm($data) {
		$errors = array();

		if (trim($data['bodytext']) == '') {
			$errors['bodytext'] = 'Prosím, vyplňte správu';
		}
		
		if (!$data['fk_from_user_id']) {
			$errors['user'] = 'Musíte byť prihlásený';
		}
		
		if ($errors) {
			return $errors;
		}
		return TRUE;
	}
	
	protected function prepareDataToSave($data) {
		unset($data['chat']);
		
		$data['pid'] = 111;	// TOTO by malo byt v configu ale zadara sa mi to nechce robit :)
		$data['crdate'] = time();
		$data['tstamp'] = time();
		
		return $data;
	}
}

?>